<?php
class Weixin_weixin_model extends CI_Model
{
    public $table_menu;
    public $table_setting;
    public $table_card;
    public $sid;

    public function __construct()
    {
        parent::__construct();

        $this->sid = $GLOBALS['sid'];
        $this->data = $GLOBALS['config'];
        $this->table_menu = 'weixin_menu';
        $this->table_setting = 'weixin_setting';
        $this->table_card = 'weixin_card';
        $this->table_news_list = 'weixin_news_list';
        $this->table_news_row  = 'weixin_news_row';
        $this->table_user  = $this->db->dbprefix('user');
        $this->table_user_expand  = $this->db->dbprefix('user_expand');

        $this->setting = $this->db_get_setting();
        define('TOKEN',     @$this->setting['token']);
        define('APPID',     @$this->setting['appid']);
        define('APPSECRET', @$this->setting['appsecret']);

        $this->load->driver('cache');
        $this->load->library('Curl');
    }

    public function __call($method, $args)
    {
        echo "Method $method Not Exists!";
    }

    public function valid()
    {
        @$echoStr = $_GET["echostr"];

        if($echoStr)
        {
            //valid signature , option
            if($this->checkSignature()){
                echo $echoStr;
                exit;
            }
        }
    }

    public function responseMsg()
    {
        //get post data, May be due to the different environments
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        logger("※\t postStr:".$postStr);
        if (!empty($postStr))
        {
            /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
               the best way is to check the validity of xml by yourself */
            libxml_disable_entity_loader(true);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $msgType = 'response_' . strtolower($postObj->MsgType);
            $this->$msgType($postObj);
        }
        else
        {
            echo "";
            exit;
        }
    }

    /**
     * 菜单事件
     *
     * @param $postObj
     */
    public function response_event($postObj)
    {
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;

        if($postObj->Event == 'subscribe')
        {
          $this->response_event_subscribe($fromUsername,$toUsername);
        }
    }


    /**
     * 关注事件
     *
     * @param $postObj
     */
    public function response_event_subscribe($fromUsername, $toUsername)
    {
        $welcome = strlen(trim($this->data['wx_follow_welcome_info'])) ? $this->data['wx_follow_welcome_info'] : '欢迎关注' . $this->data['company'] . '公众号';
        $this->makeText($fromUsername, $toUsername, $welcome);
    }


    public function initialize_login($open_id = '')
    {

        if(empty($open_id)) return false;

        $query = $this->db->get_where($this->table_user,array('openid' => $open_id,'sid'=>$this->sid),1);

        $row =  $query->row_array();
        if (!empty($row))
        {
            $this->session->set_userdata('user_id', $row['user_id']);
            $this->session->set_userdata('username', $row['username']);
            $this->session->set_userdata('identity_sign', $row['username']);
            $this->session->set_userdata('email', $row['email']);
            $this->session->set_userdata('mobile', $row['mobile']);
            $this->session->set_userdata('is_login', '1');
        }
        else
        {

            $winfo = $this->get_user_info($open_id);

            $login_date = $reg_date = date('Y-m-d H:i:s',$winfo['subscribe_time']);
            $login_ip = $reg_ip = $this->input->ip_address();

            $insert = array(
                'sid' => $this->sid,
                'login_date' => $login_date,
                'username' => $winfo['nickname'],
                'reg_date' => $reg_date,
                'city' => $winfo['city'],
                'country' => $winfo['country'],
                'province' => $winfo['province'],
                'login_ip' => $login_ip,
                'reg_ip' => $reg_ip,
                'status' => 1,
                'openid' => $open_id
            );

            $this->db->insert($this->table_user, $insert);
            $user_id = $this->db->insert_id();
            if ($user_id)
            {

                $data = array(
                    'sid' => $this->sid,
                    'user_id' => $user_id,
                    'gender' => $winfo['sex'],
                    'avatar' => $winfo['headimgurl']
                );

                $this->db->insert($this->table_user_expand,$data);

                $this->session->set_userdata('user_id', $user_id);
                $this->session->set_userdata('username', $row['username']);
                $this->session->set_userdata('is_login', '1');
                $this->session->set_userdata('identity_sign', $row['username']);
            }
        }
        return true ;
    }

    /**
     * 文本消息
     *
     * @param $postObj
     */
    public function response_text($postObj)
    {

        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $keyword = trim($postObj->Content);

        if(!empty( $keyword ))
        {
            $text_data = array(
                'sid'=>$GLOBALS['sid'],
                'from_username'=>strval($fromUsername),
                'content'=>$keyword,
                'crts'=>date('Y-m-d H:i:s')
            );
            _add_weixin_response_text($text_data);  // 存储响应消息
            $font = substr(str_replace('＠','@',$keyword), 0, 2);
            if($font == '@@') {
                $mobile = substr($keyword, 2);
                $binded = $this->db_bind_card($mobile, strval($fromUsername));
                if ($binded === TRUE) {
                    $this->makeText($fromUsername, $toUsername, '绑定成功，回复“1”或“微名片”查看微名片。');
                } else if ($binded === -1) {
                    $this->makeText($fromUsername, $toUsername, '您已绑定帐号，回复“解绑”进行解绑。');
                } else if ($binded === -2) {
                    $this->makeText($fromUsername, $toUsername, '该手机号已经被占用。');
                }else if ($binded === -3){
                        $this->makeText($fromUsername, $toUsername, '该手机号不存在。');
                } else {
                    $this->makeText($fromUsername, $toUsername, '您已绑定或号码不存在。');
                }
            }else if(substr($keyword, 0, 6) == '解绑'){
                if($this->db_unbind_card($fromUsername)){
                    $this->makeText($fromUsername, $toUsername, '解绑成功，如需绑定请回复“@@[手机号]”。');
                }else{
                    $this->makeText($fromUsername, $toUsername, '解绑失败。');
                }
            }else if($keyword == '1' || $keyword == '微名片' || $keyword == '名片'){
                $row = $this->db_get_expert_by_openid($fromUsername);
                if($row){
                    $item = array(
                        'items' =>
                            array(
                                array(
                                    'title' => $row['realname'],
                                    'description' => '',
                                    'picurl' => URLPIC.$row['avatar'],
                                    'url' => site_url('mobile/member/card/?eid='.$row['id'])
                                )
                            )
                    );
                    $this->makeNews($fromUsername, $toUsername, $item);
                }else{
                    $this->makeText($fromUsername, $toUsername, '请回复"@@[手机号]"，进行绑定。');
                }
            }else{


                //========================微店绑定功能,暂停开发,20150925=============================================

                /*$font = substr($keyword, 0, 6);
                  if($font == '绑定')
                  {
                      $mobile = substr($keyword, 6);
                      $binded = _bind_weixin_shop($mobile, strval($fromUsername));
                      $this->makeText($fromUsername, $toUsername, $binded);
                      if ($binded == TRUE) {
                          $this->makeText($fromUsername, $toUsername, '绑定成功，回复“微店”查看微店。');
                      }else if ($binded === -1) {
                          $this->makeText($fromUsername, $toUsername, '您已绑定帐号，回复“解绑微店”进行解绑。');
                      }else{
                          $this->makeText($fromUsername, $toUsername, '您已绑定微店或该手机用户不存在。');
                      }
                  }
                  if($keyword == '微店')
                  {
                      $row = _get_shop_by_openid(strval($fromUsername));
                      if($row)
                      {
                          $this->makeNews($fromUsername, $toUsername, $row);
                      }else{
                          $this->makeText($fromUsername, $toUsername, '请回复"绑定[手机号]"，进行绑定。');
                      }
                  }
                  if($keyword == '解绑微店')
                  {
                      if(_unbind_weixin_shop(strval($fromUsername))){
                          $this->makeText($fromUsername, $toUsername, '解绑成功，如需绑定请回复“绑定[手机号]”。');
                      }else{
                          $this->makeText($fromUsername, $toUsername, '解绑失败。');
                      }
                  }*/
                //===============================================================================================

                $item = _process_weixin_response_text($keyword); // 处理响应消息
                if(!empty($item)&&is_array($item))
                {
                    $this->makeNews($fromUsername, $toUsername, $item);
                }
                $this->make_transfer_customer_service($fromUsername, $toUsername);
            }
        }else{
            $this->make_transfer_customer_service($fromUsername, $toUsername);
        }
    }

    private function makeText($fromUsername,$toUsername,$text='',$FuncFlag=0)
    {
        $textTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[text]]></MsgType>
            <Content><![CDATA[%s]]></Content>
            <FuncFlag>0</FuncFlag>
            </xml>";
        echo sprintf($textTpl,$fromUsername,$toUsername,time(),$text,$FuncFlag);
        exit;
    }

    /**
     * 转发到多客服
     *
     * @param $fromUsername
     * @param $toUsername
     */
    private function make_transfer_customer_service($fromUsername,$toUsername)
    {
        $textTpl = "<xml>
             <ToUserName><![CDATA[%s]]></ToUserName>
             <FromUserName><![CDATA[%s]]></FromUserName>
             <CreateTime>%s</CreateTime>
             <MsgType><![CDATA[transfer_customer_service]]></MsgType>
         </xml>";
        echo sprintf($textTpl,$fromUsername,$toUsername,time());
        exit;
    }


    /**
     * 回复图文消息
     *
     * @param $fromUsername
     * @param $toUsername
     * @param array $newsData
     * @param int $FuncFlag
     */
    private function makeNews($fromUsername,$toUsername,$newsData=array(),$FuncFlag=0)
    {
        $newTplHeader = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[news]]></MsgType>
            <ArticleCount>%s</ArticleCount><Articles>";
        $newTplItem = "<item>
            <Title><![CDATA[%s]]></Title>
            <Description><![CDATA[%s]]></Description>
            <PicUrl><![CDATA[%s]]></PicUrl>
            <Url><![CDATA[%s]]></Url>
            </item>";
        $newTplFoot = "</Articles>
            <FuncFlag>0</FuncFlag>
            </xml>";
        $Content = '';
        $itemsCount = count($newsData['items']);
        $itemsCount = $itemsCount < 10 ? $itemsCount : 10;//微信公众平台图文回复的消息一次最多10条
        if ($itemsCount) {
            foreach ($newsData['items'] as $key => $item) {
                if ($key<=9) {
                    $Content .= sprintf($newTplItem,$item['title'],$item['description'],$item['picurl'],$item['url']);
                }
            }
        }
        $header = sprintf($newTplHeader,$fromUsername,$toUsername,time(),$itemsCount);
        $footer = sprintf($newTplFoot,$FuncFlag);
        echo $header . $Content . $footer;
        exit;
    }

    private function makeMusic($fromUsername,$toUsername,$newsData=array(),$FuncFlag=0)
    {
        $newTplHeader = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[music]]></MsgType>
            <Music>";
        $newTplItem = "<Title><![CDATA[%s]]></Title>
            <Description><![CDATA[%s]]></Description>
            <MusicUrl><![CDATA[%s]]></MusicUrl>
            <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>";
        $newTplFoot = "</Music>
            <FuncFlag>0</FuncFlag>
            </xml>";
        $Content = sprintf($newTplItem,$newsData['title'],$newsData['description'],$newsData['url'],$newsData['durl']);
        $header = sprintf($newTplHeader,$fromUsername,$toUsername,time());
        $footer = sprintf($newTplFoot,$FuncFlag);
        echo $header . $Content . $footer;
        exit;
    }

    private function checkSignature()
    {
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }

        @$signature = $_GET["signature"];
        @$timestamp = $_GET["timestamp"];
        @$nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    /**
     * @return string
     */
    public function __get_access_token()
    {
        $access_token = '';
        if(!defined('APPID') || !defined('APPSECRET'))
        {
            return $access_token;
        }

//        $cache_key = 'acstk_'.SITEID.APPID.APPSECRET;
//        $access_token = $this->cache->file->get($cache_key);
//        if(!$access_token)
//        {
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.APPID.'&secret='.APPSECRET;


         $ret = file_get_contents($url);


            $ret = json_decode($ret, TRUE);


            if(!empty($ret['access_token']))
            {
                $access_token = $ret['access_token'];

//                $this->cache->file->save($cache_key, $access_token, 3600);
            }
//        }


        return $access_token;
    }

    /**
     * WEIXIN JSAPI
     *
     * @param $noncestr
     * @param $acurl
     * @param $timestamp
     * @return string
     */
    public function __get_jsapi_ticket($noncestr, $acurl, $timestamp)
    {
        global $config;
        if(empty($config['appid']) || empty($config['appsecret'])){
            return '';
        }

        $access_token = self::__get_access_token();


        $cache_key = 'jsapi_'.SITEID;
        $signature = $this->cache->file->get($cache_key);
        if(!$signature)
        {
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$access_token&type=jsapi";
            $ret = file_get_contents($url);

            $ret = json_decode($ret, TRUE);
            if($ret['ticket']){
                $string1 = "jsapi_ticket=$ret[ticket]&noncestr=$noncestr&timestamp=$timestamp&url=$acurl";

                $signature = sha1( $string1 );
                $this->cache->file->save($cache_key, $signature, 3600);
            }
        }
        return $signature;
    }
    /**
     * @return mixed|string
     */
    public function get_menus($format = FALSE)
    {
        $ret = $this->db_get_menu($format);
        if(empty($ret))
        {
            $access_token = $this->__get_access_token();
            $url = 'https://api.weixin.qq.com/cgi-bin/menu/get?access_token='.$access_token;
            $remote_ret = file_get_contents($url);
            $remote_ret = json_decode($remote_ret, TRUE);

            $this->db_init_menu($remote_ret);
            $ret = $this->db_get_menu($format);
        }
        return $ret;
    }


    public function curl_execute($json = '', $host)
    {

        if (!empty($json))
        {
            $extend = array(
                CURLOPT_BUFFERSIZE => 10,
                CURLOPT_TIMEOUT => 25,
                CURLOPT_POSTFIELDS => $json,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_HTTPHEADER => array(
                    'Content-Type: application/json',
                    'Content-Length: ' . strlen($json)
                )
            );

            $result = $this->curl->simple_post($host, array(), $extend);
            return $result;
        }
    }

    public function send_menu($menu_string)
    {
        $access_token = $this->__get_access_token();
        $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$access_token;
        return $this->curl_execute($menu_string,$url);
    }

    /**
     * @param $openid
     * @return string
     */
    public function get_user_info($openid)
    {
        $openid = strval($openid);
        $access_token = $this->__get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
        $remote_ret = file_get_contents($url);
        $remote_ret = json_decode($remote_ret, TRUE);
        return $remote_ret;
    }

    public function get_user_group()
    {
        $access_token = $this->__get_access_token();
        $cache_key = 'usergroups'.SITEID;
        $remote_ret = $this->cache->file->get($cache_key);
        if(!$remote_ret) {
            $url = "https://api.weixin.qq.com/cgi-bin/groups/get?access_token=$access_token";
            $remote_ret = file_get_contents($url);
            $remote_ret = json_decode($remote_ret, TRUE);
            if($remote_ret && !$remote_ret['errcode']){
                $this->cache->file->save($cache_key, $remote_ret, 3600);
            }
        }
        return $remote_ret;
    }

    public function create_group($groupname)
    {
        $access_token = $this->__get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/groups/create?access_token=$access_token";
        $send = array(
            'group' => array(
                'name' => $groupname
            )
        );
        $send_string = json_encode_ex($send);
        $ret = http_post_data($url, $send_string);

        $cache_key = 'usergroups'.SITEID;
        $this->cache->file->delete($cache_key);
        return $ret['errcode'] ? 0 : 1;
    }

    public function update_group($groupid, $groupname)
    {
        $access_token = $this->__get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/groups/update?access_token=$access_token";
        $send = array(
            'group' => array(
                'id'  => $groupid,
                'name' => $groupname
            )
        );
        $send_string = json_encode_ex($send);
        $ret = http_post_data($url, $send_string);

        $cache_key = 'usergroups'.SITEID;
        $this->cache->file->delete($cache_key);

        return $ret['errcode'] ? 0 : 1;
    }

    public function delete_group($groupid)
    {
        $access_token = $this->__get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/groups/delete?access_token=$access_token";
        $send = array(
            'group' => array(
                'id'  => $groupid,
            )
        );
        $send_string = json_encode_ex($send);
        $ret = http_post_data($url, $send_string);

        $cache_key = 'usergroups'.SITEID;
        $this->cache->file->delete($cache_key);

        return $ret['errcode'] ? 0 : 1;
    }

    public function upload_image($file){
        $access_token = $this->__get_access_token();
        $url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=$access_token&type=image";
        $remote_ret = http_post_formdata($url, 'media', $file);
        if($remote_ret['errmsg']){
            return $remote_ret;
        }
        return @$remote_ret['media_id'];
    }

    /**
     * 上传图文消息素材
     */
    public function send_articles($id)
    {
//        $list_info = $this->db_get_news_list_by_id($id);

        $access_token = $this->__get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=$access_token";
        $data = $this->db_news_row_by_listid($id);
        $articles = array();
        foreach ($data as $row) {
            $articles[] = array(
                'thumb_media_id'     => $row['thumb_media_id'],
                'author'             => $row['author'],
                'title'              => $row['title'],
                'content_source_url' => $row['content_source_url'],
                'content'            => $row['content'],
                'digest'             => $row['digest'],
                'show_cover_pic'     => $row['show_cover_pic'],
            );
        }
        $send_data['articles'] = $articles;

        $send_string = json_encode_ex($send_data);
        $ret = http_post_data($url, $send_string);
        $this->db_update_news_list(array('media_id' => $ret['media_id']), $id);
        return TRUE;
    }

    public function do_article_send($id)
    {
        $list_info = $this->db_get_news_list_by_id($id);
        if(empty($list_info['media_id']) || !empty($list_info['msg_id'])){
//            return FALSE;
        }
        $access_token = $this->__get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=$access_token";

        $send = array();
        if($list_info['group_id'] != -1)
        {
            $send['filter']['group_id'] = $list_info['group_id'];
        }
        $send['mpnews']['media_id'] = $list_info['media_id'];
        $send['msgtype'] = 'mpnews';

        $send_string  = json_encode_ex($send);
        $ret = http_post_data($url, $send_string);
        if(isset($ret['errcode']) && $ret['errcode'] == 0){
            $this->db_update_news_list(array('msg_id' => $ret['msg_id']), $id);
            return TRUE;
        }else{
            return $ret;
        }
    }

    public function get_fanslist($next_openid = '')
    {
        $access_token = $this->__get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=$access_token&next_openid=$next_openid";
        $res = file_get_contents($url);
        $data = json_decode($res, true);
        return $data;
    }

    public function get_batch_fansinfo($param = array())
    {
        $param = array_values($param);
        $access_token = $this->__get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=$access_token";

        foreach ($param as $k => $v) {
            $list[$k]['openid'] = $v;
            $list[$k]['lang'] = 'zh-CN';
        }

        $send = array('user_list' => $list);
        $send_string  = json_encode_ex($send);
        $ret = http_post_data($url, $send_string);

        return $ret['user_info_list'] ? $ret['user_info_list'] : array();
    }

    public function move_group($to_groupid, $openids = array())
    {
        $access_token = $this->__get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/groups/members/batchupdate?access_token=$access_token";
/*{"openid_list":["oDF3iYx0ro3_7jD4HFRDfrjdCM58","oDF3iY9FGSSRHom3B-0w5j4jlEyY"],"to_groupid":108}*/
        $send['openid_list'] = $openids;
        $send['to_groupid'] = $to_groupid;
        $send_string  = json_encode_ex($send);
        $ret = http_post_data($url, $send_string);
        return !$ret['errcode'];
    }

    //===============================================================================================
    //===============================================================================================
    //===============================================================================================
    //===============================================================================================
    //===============================================================================================
    //===============================================================================================
    //===============================================================================================
    //===============================================================================================
    //===============================================================================================
    //===============================================================================================

    public function db_get_setting()
    {
        $this->db->select('*');
        $this->db->where(array(
            'sid' => $GLOBALS['sid']
        ));
        $query = $this->db->get($this->table_setting);
        $data = array();
        foreach ($query->result_array() as $row) {
            $data[$row['key']] = $row['value'];
        }
        return $data;
    }

    public function db_setting($data = array())
    {
        foreach ($data as $k => $v) {
            $this->db->query("REPLACE INTO {$this->db->dbprefix}{$this->table_setting} SET `sid`=?, `value`=?, `key`=?", array(
                $GLOBALS['sid'], trim($v), trim($k)
            ));
        }

        return TRUE;
    }

    public function db_init_menu($ret)
    {
        if(empty($ret['menu'])){
            return FALSE;
        }
        $i = 0;
        foreach ($ret['menu']['button'] as $key => $root)
        {
            $pid = $this->db_save_menu(array(
                'name' => $root['name'],
                'displayorder' => $i++,
                'url' => strval($root['url']),
                'type' => strval($root['type']),
            ));
            foreach($root['sub_button'] as $k => $sub){
                unset($sub['sub_button']);
                $sub['parent_id']    = $pid;
                $sub['displayorder'] = $i ++;
                $this->db_save_menu($sub);
            }
        }
        return TRUE;
    }

    /**
     * 存储menu在数据库
     *
     * @param array $menu
     * @return int
     */
    public function db_save_menu($menu = array(), $id = 0)
    {
        if(empty($menu)){
            return 0;
        }
        if($id> 0)
        {
            return $this->db->update($this->table_menu, $menu, array('id' => $id, 'sid' => $GLOBALS['sid']));
        }
        else
        {
            $menu['sid'] = $GLOBALS['sid'];
            $this->db->insert($this->table_menu, $menu);
            return $this->db->insert_id();
        }
    }

    /**
     * 从数据库读取menu
     *
     * @return mixed
     */
    public function db_get_menu($format = FALSE, $fields = '*')
    {
        $data = array();
        $this->db->select('*');
        $this->db->where(array(
            'sid' => $GLOBALS['sid']
        ));
        $this->db->order_by('parent_id ASC');
        $this->db->order_by('displayorder ASC');
        $query = $this->db->get($this->table_menu);
        $list = $query->result_array();
        foreach ($list as $row)
        {
            if($format){
                $pid = $row['parent_id'];
                $id = $row['id'];
                unset($row['id'], $row['parent_id']);

                if($row['type'] == 'click'){
                    unset($row['url']);
                }else if($row['type'] == 'view'){
                    unset($row['key']);
                }else{
                    unset($row['key'], $row['url'], $row['type']);
                }

                if( $fields != '*'){
                    foreach ($row as $k => $v) {
                        if(!in_array($k, explode(',', $fields))){
                            unset($row[$k]);
                        }
                    }
                }

                if($pid != 0)
                {
                    $data[$pid]['sub_button'][] = $row;
                }
                else
                {
                    $data[$id] = $row;
                }
            }else{
                $data[] = $row;
            }
        }

        return $data;
    }


    public  function db_get_general_menu(){
        $this->db->select('*');
        $this->db->where(array(
            'sid' => $GLOBALS['sid']
        ));
        $this->db->order_by('parent_id ASC');
        $this->db->order_by('displayorder ASC');
        $query = $this->db->get($this->table_menu);
        return $query->result_array();
    }

    public function db_menu_del($id)
    {
        $sql = "DELETE from {$this->db->dbprefix}{$this->table_menu} where (id=$id OR parent_id=$id) AND sid='$GLOBALS[sid]'";
        return  $this->db->query($sql);
    }

    public function db_menu_clear()
    {
        $sql = "DELETE from {$this->db->dbprefix}{$this->table_menu} where sid='$GLOBALS[sid]'";
        return  $this->db->query($sql);
    }

    public function db_get_menu_by_id($id)
    {
        $fields = '*';
        $this->db->select($fields);
        $this->db->where(array(
            'sid' => $GLOBALS['sid'],
            'id' => $id
        ));
        $query = $this->db->get($this->table_menu);
        return $query->row_array();
    }

    /**
     * @param array $admin_ids
     * @return mixed
     */
    public function db_get_card_bind($admin_ids = array())
    {
        $ids = array();
        foreach ($admin_ids as $admin_id) {
            if(is_array($admin_id)){
                $ids[] = $admin_id['id'];
            }else{
                $ids[] = $admin_id;
            }
        }

        $this->db->select('*');
        if(!empty($ids)){
            $this->db->where_in('admin_id', $ids);
        }
        $this->db->where(array(
            'sid' => $GLOBALS['sid'],
            )
        );
        $query = $this->db->get($this->table_card);
        $data = array();
        foreach ($query->result_array() as $row) {
            $data[$row['admin_id']] = $row;
        }
        return $data;
    }

    public function db_bind_card($mobile, $openid)
    {
        $openid = strval($openid);
        $admin_user = 'admin_user';
        $this->db->select('id');
        $this->db->where('mobile', $mobile);
        $this->db->where('sid', $GLOBALS['sid']);
        $query = $this->db->get($admin_user);
        $row = $query->row_array();
        if(empty($row))
        {
            return FALSE;
        }
        $admin_id = $row['id'];

        if ($this->is_bind_card($openid)) {

            return -1;
        }
        if ($this->is_mobile_use_check($mobile))
        {
            return -2;
        }
        $this->db->insert($this->table_card, array(
            'admin_id' => $admin_id,
            'openid' => $openid,
            'bindts' => date('Y-m-d H:i:s'),
            'sid'    => $GLOBALS['sid']
        ));
        return TRUE;
    }

    public function db_unbind_card($openid = '', $admin_id = ''){
        $openid = strval($openid);
        if($openid) {
            $this->db->where('openid', $openid);
        }
        if($admin_id){
            $this->db->where('admin_id', $admin_id);
        }
        $this->db->where('sid', $GLOBALS['sid']);
        $this->db->delete($this->table_card);
        return $this->db->affected_rows();
    }

    public function is_bind_card($openid)
    {
        $openid = strval($openid);
        $query = $this->db->get_where($this->table_card, array('openid' => $openid,'sid' => $GLOBALS['sid']));
        $row = $query->row_array();
        return empty($row) ? FALSE : TRUE;
    }

    public function is_mobile_use_check($mobile)
    {
        $a = $this->db->dbprefix('admin_user');
        $c     = $this->db->dbprefix($this->table_card);
        $where = "$a.mobile = $mobile AND $a.sid = {$GLOBALS['sid']}";
        $this->db->select($c.'.admin_id');
        $this->db->join($a, "$a.id = $c.admin_id",'left');
        $this->db->where($where, NULL, FALSE);
        $query = $this->db->get($c);
        $row = $query->row_array();
        return empty($row) ? FALSE : TRUE;
    }

    public function db_get_expert_by_openid($openid)
    {
        $openid = strval($openid);
        $table_admin_user = $this->db->dbprefix('admin_user');
        $table_expert     = $this->db->dbprefix('expert');
        $table_card     = $this->db->dbprefix($this->table_card);
        $sql = "SELECT * from $table_card as a,$table_admin_user as b, $table_expert as c where a.admin_id=b.id and b.id=c.id AND a.sid='$GLOBALS[sid]' AND openid=? LIMIT 1";
        $query = $this->db->query($sql, array($openid));
        $row = $query->row_array();
        return !empty($row) ? $row : array();
    }

    /**
     * 初始化列表
     *
     * @return mixed
     */
    public function db_news_init_list()
    {
        $this->db->where('sid', $GLOBALS['sid']);
        $this->db->where('status', '0');
        $this->db->delete($this->table_news_list);
        $this->db->insert($this->table_news_list, array(
            'status' => 0,
            'crts'   => time(),
            'sid'    => $GLOBALS['sid'],
        ));
        return $this->db->insert_id();
    }

    public function db_get_news_list()
    {
        $this->db->select('*');
        $this->db->where('sid', $GLOBALS['sid']);
        $this->db->where('status', '1');
        $this->db->order_by('id DESC');
        $query = $this->db->get($this->table_news_list);
        return $query->result_array();
    }

    function db_get_news_list_by_id($id){
        $this->db->select('*');
        $this->db->where('sid', $GLOBALS['sid']);
        $this->db->where('id', $id);
        $query = $this->db->get($this->table_news_list);
        return $query->row_array();
    }

    public function db_update_news_list($row, $id)
    {
        $row['upts'] = time();
        $row['status'] = '1';
        $row['sid']  = $GLOBALS['sid'];
        $this->db->update($this->table_news_list, $row, array(
            'id' => $id
        ));
        return TRUE;
    }

    public function db_news_list_delete_by_id($id)
    {
        $this->db->where('id', $id);
        $this->db->where('sid', $GLOBALS['sid']);
        $this->db->delete($this->table_news_list);

        $this->db->where('sid', $GLOBALS['sid']);
        $this->db->where('list_id', $id);
        $this->db->delete($this->table_news_row);
        return TRUE;
    }

    public function db_insert_news_row($data)
    {
        if(!$data['list_id']){
            return FALSE;
        }
        $data['sid'] = $GLOBALS['sid'];
        $this->db->insert($this->table_news_row, $data);
        $this->db->update($this->table_news_list, array(
            'status' => 1,
            'sid' => $GLOBALS['sid']
        ), array(
            'id' => $data['list_id'],
            'sid' => $GLOBALS['sid']
        ));
        return TRUE;
    }

    public function db_update_news_row($data, $id)
    {
        $this->db->update($this->table_news_row, $data, array(
            'id' => $id,
            'sid' => $GLOBALS['sid']
        ));
        return TRUE;
    }

    public function db_news_row_by_listid($list_id)
    {
        $this->db->select('*');
        $this->db->where('sid', $GLOBALS['sid']);
        $this->db->where('list_id', $list_id);
        $this->db->order_by('displayorder ASC');
        $query = $this->db->get($this->table_news_row);
        return $query->result_array();
    }

    public function db_news_row_by_id($id)
    {
        $this->db->select('*');
        $this->db->where('sid', $GLOBALS['sid']);
        $this->db->where('id', $id);
        $query = $this->db->get($this->table_news_row);
        return $query->row_array();
    }

    public function db_news_row_delete_by_id($id)
    {
        $this->db->where('sid', $GLOBALS['sid']);
        $this->db->where('id', $id);
        $this->db->delete($this->table_news_row);
        return TRUE;
    }
}